# coding: utf-8
# Author: legend
# @Time： 2020/8/27 下午10:05
import json
import os

import xlwt
import yaml
from ngs.time import us_timestamp_to_str


def mkdirs(paths: list):
    for path in paths:
        if not os.path.exists(path):
            os.makedirs(path)


def load_json_file(path):
    content = ''
    with open(path, 'rb') as f:
        line = f.readline()
        while line:
            content += line.decode()
            line = f.readline()
    return json.loads(content)


def dump_json_file(path, data):
    with open(path, 'wb+', encoding='utf-8') as f:
        f.write(data)


def load_yaml_file(path):
    assert os.path.isfile(path), '"{}"文件不存在'.format(path)
    with open(path, 'r', encoding='utf-8') as f:
        content = f.read()
    return yaml.load(content, Loader=yaml.FullLoader)


def dump_yaml_file(path, data):
    with open(path, 'w+', encoding='utf-8') as f:
        yaml.dump(data, f, default_flow_style=False, encoding="utf-8", allow_unicode=True)


def write_pid(output_path, pyinstaller_mode=False):
    """
    将程序进程ID输出到pid文件, pyinstaller打包模式下输出父进程ID
    :param output_path:
    :param pyinstaller_mode:
    :return:
    """
    if pyinstaller_mode:
        pid = os.getppid()
    else:
        pid = os.getpid()
    with open(output_path, 'w') as f:
        f.write(str(pid))

    return pid


def wirte_data_to_wb(table_headers, table_fields, table_data):
    """
    写入表格中
    :param table_headers: 表头
    :param table_fields: 字段
    :param table_data: 数据
    :return:
    """
    wb = xlwt.Workbook(encoding='utf-8')
    ws = wb.add_sheet('sheet')
    font_style = xlwt.XFStyle()
    font_style.font.bold = True
    for alias_index, alias in enumerate(table_headers):
        ws.write(0, alias_index, alias, font_style)
    font_style = xlwt.XFStyle()
    for field_name_index, field_name in enumerate(table_fields):
        row_num = 0
        for running in table_data:
            row_num += 1
            try:
                if field_name in ['boot_time', 'start_time']:
                    ws.write(row_num, field_name_index, us_timestamp_to_str(running[field_name]), font_style)
                else:
                    ws.write(row_num, field_name_index, running[field_name], font_style)
            except:
                ws.write(row_num, field_name_index, '', font_style)
    return wb
